//
//  QinKeyBoardController.m
//  自定义聊天界面和键盘-多选照片-语音-表情-文本
//
//  Created by qinlongqing on 14-10-13.
//  Copyright (c) 2014年 qinlongqing. All rights reserved.
//

#import "QinKeyBoardController.h"
#import "ConsultingChatViewController.h"
static QinKeyBoardController *instance = nil;

@interface QinKeyBoardController ()<UITextViewDelegate,SendFaceDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    CGFloat keyboardToolViewHeight;//tool的高度

    CGRect keyboardRect;//系统键盘的高度
    double keyboardAnimationDuration;//弹出键盘所需要的时间
    
    BOOL isSystemControllerKeyboard;//用于区分是否是系统键盘
    
    
    NSMutableArray *faceRangeInTextField;//发送的表情在UITextField中得Range
    NSRange didEndEditCursorPosition;//结束编辑时光标的位置
}

@end

@implementation QinKeyBoardController
@synthesize  messageInputView,sendAudioView,sendFaceView,sendPhotoView;

+ (QinKeyBoardController *)instance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        instance = [self new];
        
        [instance initializeData];

    });
    
    return instance;
}

- (void)initializeData{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    isSystemControllerKeyboard = YES;//默认是通过系统，自动调节tool的高度
}

#pragma 当设置自定义键盘的viewController时，创建键盘上的所有元素
- (void)setViewController:(UIViewController *)viewController{
    
    
    if (![viewController isEqual:_viewController]) {
        _viewController = viewController;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doTap:)];
        [self.tableview addGestureRecognizer:tap];
//        [tap release];
        
#pragma 创建自定义toolBar
        if (CurrentSystemIsAbove_IOS7) {
            keyboardToolViewHeight = 45.0f;
        }
        else{
            keyboardToolViewHeight = 40.0f;
        }
        messageInputView = [[QinMessageInputView alloc]initWithFrame:CGRectMake(0, kScreenHeight - keyboardToolViewHeight-64, [[UIScreen mainScreen] bounds].size.width, keyboardToolViewHeight)];
        messageInputView.backgroundColor = [UIColor whiteColor];
        [self.viewController.view addSubview:messageInputView];
//        [messageInputView release];
        messageInputView.inputTextView.delegate = self;//在这里设置textField的代理
        [self createSendAudioView];
        [self createSendFaceView];
        [self createSendPhotoView];
    }
    self.previousTextViewContentHeight=34;
}

- (void)doTap:(UITapGestureRecognizer *)tapGesture{
    if (messageInputView.frame.origin.y != [[UIScreen mainScreen] bounds].size.height - keyboardToolViewHeight) {
        messageInputView.sendFaceButton.selected = NO;
        messageInputView.sendPhotoButton.selected = NO;
        messageInputView.showOrHiddenSendAudioButton.selected = YES;
        if (isSystemControllerKeyboard == NO) {//自定义键盘
            [self hiddenCustomKeyboardToolAnimation];
        }
        else{//系统键盘
            [self hiddenSystemKeyboardToolAnimation];
        }
    }
}
- (void)downMytableview
{
    if (messageInputView.frame.origin.y != [[UIScreen mainScreen] bounds].size.height - keyboardToolViewHeight- 64) {
        messageInputView.sendFaceButton.selected = NO;
        messageInputView.sendPhotoButton.selected = NO;
        messageInputView.showOrHiddenSendAudioButton.selected = YES;
        if (isSystemControllerKeyboard == NO) {//自定义键盘
            
            [self hiddenCustomKeyboardToolAnimation];
        }
        else{//系统键盘
            [self hiddenSystemKeyboardToolAnimation];
        }
    }
}

#pragma QinMessageInputView中的UITextView的delegate方法
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    [self showSystemKeyboardToolAnimation:YES withSender:nil];
    
    if(!self.previousTextViewContentHeight){
        self.previousTextViewContentHeight = textView.contentSize.height;
    }
    return YES;
}
- (void)adjustTextViewHeightBy:(CGFloat)changeInHeight
{
    CGRect prevFrame = messageInputView.inputTextView.frame;
    
    NSInteger numLines = MAX([messageInputView numberOfLinesOfText],[messageInputView numberOfLines]);
    
    messageInputView.inputTextView.frame = CGRectMake(prevFrame.origin.x,
                                     prevFrame.origin.y,
                                     prevFrame.size.width,
                                     prevFrame.size.height + changeInHeight);
    
    messageInputView.inputTextView.contentInset = UIEdgeInsetsMake((numLines >= 3 ? 4.0f : 0.0f),
                                                  0.0f,
                                                  (numLines >= 3 ? 4.0f : 0.0f),
                                                  0.0f);
    
//    messageInputView.inputTextView.scrollEnabled = (numLines >= 3);
    
    
    
//    if(numLines >=3) {
//        CGPoint bottomOffset = CGPointMake(0.0f, messageInputView.inputTextView.contentSize.height - messageInputView.inputTextView.bounds.size.height);
//        [messageInputView.inputTextView setContentOffset:bottomOffset animated:YES];
//    }
}
- (void)textViewDidChange:(UITextView *)textView
{
    CGSize size = [textView sizeThatFits:CGSizeMake(textView.frame.size.width, 70)];
    
    BOOL isShrinking = size.height < self.previousTextViewContentHeight;
    CGFloat changeInHeight = size.height - self.previousTextViewContentHeight;
    
    if(!isShrinking && self.previousTextViewContentHeight == 70) {
        changeInHeight = 0;
    }
    else {
        changeInHeight = MIN(changeInHeight, 70 - self.previousTextViewContentHeight);
    }
    if(changeInHeight != 0.0f) {

        [UIView animateWithDuration:0.25f
                         animations:^{
                             
                             if(isShrinking) {
                                 // if shrinking the view, animate text view frame BEFORE input view frame
                                 [self adjustTextViewHeightBy:changeInHeight];
                             }
                             
                             CGRect inputViewFrame = messageInputView.frame;
                             messageInputView.frame = CGRectMake(inputViewFrame.origin.x,
                                                                      inputViewFrame.origin.y - changeInHeight,
                                                                      inputViewFrame.size.width,
                                                                      inputViewFrame.size.height + changeInHeight);
                             [messageInputView resetSubviewsFrame];
                            if(!isShrinking) {
                                 [self adjustTextViewHeightBy:changeInHeight];
                             }
                        }
                         completion:^(BOOL finished) {
            }];
        self.previousTextViewContentHeight = MIN(size.height, 70);
    }
    CGPoint bottomOffset = CGPointMake(0.0f, messageInputView.inputTextView.contentSize.height - messageInputView.inputTextView.bounds.size.height);
    [messageInputView.inputTextView setContentOffset:bottomOffset animated:YES];
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
//    NSLog(@"------location=%ld  length=%ld",textView.selectedRange.location,textView.selectedRange.length);

    //    didEndEditCursorPosition = NSMakeRange(textField.selectedTextRange.start, 0);
    return YES;
}

#pragma mark - return 发送消息
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        
        //[textView resignFirstResponder];
        if ([[textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0) {
            self.messageInputView.inputTextView.text = @"";
            return NO;
        } else {
            //发送textView中的内容并置空
            if (self.messageDelegate&&[self.messageDelegate respondsToSelector:@selector(sendMessage:)]) {
                [self.messageDelegate sendMessage:self.messageInputView.inputTextView.text];
            }
            //发送之后设置相应的frame
            [self.messageInputView.inputTextView setText:@""];
            self.messageInputView.inputTextView.selectedRange=NSMakeRange(0,0);
            [self textViewDidChange:self.messageInputView.inputTextView];
            return NO;
        }
    }
    return YES;
}


#pragma 选中发送语音时，出现的view
- (void)createSendAudioView{
    sendAudioView = [[SendAudioView alloc]initWithFrame:CGRectMake(0, [[UIScreen mainScreen] bounds].size.height-64, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height - kSendAudioViewFrameHeight - 64)];
    sendAudioView.backgroundColor = [UIColor whiteColor];
    [self.viewController.view addSubview:sendAudioView];
//    [sendAudioView release];
}

#pragma 选中发送表情时，出现的view
- (void)createSendFaceView{
    sendFaceView = [[SendFaceView alloc]initWithFrame:CGRectMake(0, [[UIScreen mainScreen] bounds].size.height, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height - kSendFaceViewFrameHeight - 64)];
    sendFaceView.delegate = self;
    sendFaceView.backgroundColor = [UIColor whiteColor];

    [self.viewController.view addSubview:sendFaceView];
//    [sendFaceView release];
}
- (void)didSelectedFaceFileName:(NSString *)faceName withPlaceholderName:(NSString *)placeholderName andIsDelete:(BOOL)isDelete{
    if (faceName && placeholderName) {
        NSRange range = NSMakeRange(1, placeholderName.length - 2);
        NSString *showName = [NSString stringWithFormat:@"/%@",[placeholderName substringWithRange:range]];
        NSRange currentRange = NSMakeRange(messageInputView.inputTextView.text.length, showName.length);
        [faceRangeInTextField addObject:[NSValue valueWithRange:currentRange]];
        messageInputView.inputTextView.text = [messageInputView.inputTextView.text stringByAppendingString:showName];
        [self resetLabelHeight:messageInputView.inputTextView];
    }
}
#pragma 选中发送图片时，出现的view
- (void)createSendPhotoView{
    sendPhotoView = [[SendPhotoView alloc]initWithFrame:CGRectMake(0, [[UIScreen mainScreen] bounds].size.height, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height - kSendPhotoViewFrameHeight -64)];
    sendPhotoView.backgroundColor = [UIColor whiteColor];
    [self.viewController.view addSubview:sendPhotoView];
//    sendPhotoView.photoDelegate=self;
//    [sendPhotoView release];
}

#pragma 显示或者隐藏系统键盘和自定义键盘
- (void)showSystemKeyboardToolAnimation:(BOOL)isTextField withSender:(UIButton *)sender{
    /*当调用系统键盘时，让发送表情和发送图片的按钮恢复默认状态*/
    messageInputView.sendFaceButton.selected = NO;
    messageInputView.sendPhotoButton.selected = NO;
    /*让发送语音、发送表情和发送图片的试图消失*/
    CGRect rect = sendAudioView.frame;
    sendAudioView.frame = CGRectMake(rect.origin.x, [[UIScreen mainScreen] bounds].size.height-64, rect.size.width, rect.size.height);
    rect = sendFaceView.frame;
    sendFaceView.frame = CGRectMake(rect.origin.x, [[UIScreen mainScreen] bounds].size.height-64, rect.size.width, rect.size.height);
    rect = sendPhotoView.frame;
    sendPhotoView.frame = CGRectMake(rect.origin.x, [[UIScreen mainScreen] bounds].size.height-64, rect.size.width, rect.size.height);
    /**
     *  改变标示键盘类型为系统
     */
    isSystemControllerKeyboard = YES;
    
    /**
     *  取消第一响应者
     */
    if (!isTextField) {//如果是通过点击UITextField出现键盘，那么就不必要走下面的方法
        if (![messageInputView.inputTextView isFirstResponder]) {
            [messageInputView.inputTextView becomeFirstResponder];
            if (messageInputView.sendPhotoButton.selected==NO&&[sender isEqual:messageInputView.sendPhotoButton]) {
                messageInputView.sendPhotoButton.selected=YES;
            }
            if (messageInputView.sendFaceButton.selected==NO&&[sender isEqual:messageInputView.sendFaceButton]) {
                messageInputView.sendFaceButton.selected=YES;
            }
        }
    }
}

- (void)showCustomKeyboardToolAnimation:(CustomViewType)customViewType{//点击自定义键盘后

    
        isSystemControllerKeyboard = NO;
        CGRect rect = messageInputView.frame;
        if (customViewType == sendAudioViewType) {
            rect.origin.y = [[UIScreen mainScreen] bounds].size.height - 64 - kSendAudioViewFrameHeight - 45;
            
            CGRect audioViewRect = sendAudioView.frame;
            audioViewRect.origin.y = [[UIScreen mainScreen] bounds].size.height - 64 - kSendAudioViewFrameHeight;

            
            [UIView animateWithDuration:0.25f animations:^{
                messageInputView.frame = rect;
                sendAudioView.frame = audioViewRect;
            }];
            CGRect sendFaceViewRect = sendFaceView.frame;
            sendFaceViewRect.origin.y = [[UIScreen mainScreen] bounds].size.height-64;
            
            CGRect sendPhotoViewRect = sendPhotoView.frame;
            sendPhotoViewRect.origin.y = [[UIScreen mainScreen] bounds].size.height-64;
            
            [UIView animateWithDuration:0.1f animations:^{
                sendFaceView.frame = sendFaceViewRect;
                sendPhotoView.frame = sendPhotoViewRect;
            }];
        }
        else if (customViewType == sendFaceViewType){
            CGRect sendFaceViewRect = sendFaceView.frame;
            sendFaceViewRect.origin.y = rect.origin.y + (CurrentSystemIsAbove_IOS7?45.0f:40.0f)-64;
            //        sendFaceViewRect.origin.y = rect.origin.y + rect.size.height;
            rect.origin.y=[[UIScreen mainScreen] bounds].size.height-sendFaceViewRect.size.height-rect.size.height;
            [UIView animateWithDuration:0.25f animations:^{
                messageInputView.frame = rect;
                sendFaceView.frame = sendFaceViewRect;
            }];
            CGRect sendAudioViewRect = sendAudioView.frame;
            sendAudioViewRect.origin.y = [[UIScreen mainScreen] bounds].size.height;
            
            CGRect sendPhotoViewRect = sendPhotoView.frame;
            sendPhotoViewRect.origin.y = [[UIScreen mainScreen] bounds].size.height;
            
            [UIView animateWithDuration:0.1f animations:^{
                sendAudioView.frame = sendAudioViewRect;
                sendPhotoView.frame = sendPhotoViewRect;
            }];
        }
        else if (customViewType == sendPhotoViewType){
            rect.origin.y = [[UIScreen mainScreen] bounds].size.height - 64 - kSendPhotoViewFrameHeight - 45;
            
            CGRect sendPhotoViewRect = sendAudioView.frame;
            sendPhotoViewRect.origin.y = [[UIScreen mainScreen] bounds].size.height - 64 - kSendPhotoViewFrameHeight;
//            
            [UIView animateWithDuration:0.25f animations:^{
                messageInputView.frame = rect;
                sendPhotoView.frame = sendPhotoViewRect;
            }];
            CGRect sendAudioViewRect = sendAudioView.frame;
            sendAudioViewRect.origin.y = [[UIScreen mainScreen] bounds].size.height-64;
            
            CGRect sendFaceViewRect = sendFaceView.frame;
            sendFaceViewRect.origin.y = [[UIScreen mainScreen] bounds].size.height-64;
            
            [UIView animateWithDuration:0.1f animations:^{
                sendAudioView.frame = sendAudioViewRect;
                sendFaceView.frame = sendFaceViewRect;
            }];
        }
        
        if ([messageInputView.inputTextView isFirstResponder]) {
            [messageInputView.inputTextView resignFirstResponder];
        }
        [[NSNotificationCenter defaultCenter]postNotificationName:@"keyboard" object:nil];



}

- (void)hiddenSystemKeyboardToolAnimation{
    isSystemControllerKeyboard = YES;
    if ([messageInputView.inputTextView isFirstResponder]) {
        [messageInputView.inputTextView resignFirstResponder];
    }
}

- (void)hiddenCustomKeyboardToolAnimation{
    isSystemControllerKeyboard = NO;
//    UITableView *mTableView = [(ConsultingChatViewController *)self.viewController tableView];
    
    CGRect rect = messageInputView.frame;
    rect.origin.y = [[UIScreen mainScreen] bounds].size.height - keyboardToolViewHeight-messageInputView.frame.size.height+45-64;

    [UIView animateWithDuration:0.25f animations:^{
        messageInputView.frame = rect;
        sendAudioView.frame = CGRectMake(sendAudioView.frame.origin.x, [[UIScreen mainScreen] bounds].size.height, sendAudioView.frame.size.width, sendAudioView.frame.size.height);
        sendFaceView.frame = CGRectMake(sendFaceView.frame.origin.x, [[UIScreen mainScreen] bounds].size.height, sendFaceView.frame.size.width, sendFaceView.frame.size.height);
        sendPhotoView.frame = CGRectMake(sendPhotoView.frame.origin.x, [[UIScreen mainScreen] bounds].size.height, sendPhotoView.frame.size.width, sendPhotoView.frame.size.height);
    }];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"keyboard" object:nil];


}

- (void)keyboardWillChangeFrame:(NSNotification *)notification{//先走这个、再走willShow
    keyboardRect = [[notification.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];//将要变成的frame
    keyboardAnimationDuration = [[notification.userInfo valueForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//    NSLog(@"keyboardWillChangeFrame x=%f y=%f width=%f height=%f  duration=%f",keyboardRect.origin.x,keyboardRect.origin.y,keyboardRect.size.width,keyboardRect.size.height,keyboardAnimationDuration);
    if (isSystemControllerKeyboard) {
        if (keyboardRect.origin.y < [[UIScreen mainScreen] bounds].size.height) {//让键盘出现
            CGRect rect = messageInputView.frame;
            rect.origin.y = [[UIScreen mainScreen] bounds].size.height - CGRectGetHeight(keyboardRect) - CGRectGetHeight(rect)-64;
            [UIView animateWithDuration:keyboardAnimationDuration animations:^{
                messageInputView.frame = rect;
            } completion:^(BOOL finished) {
                
            }];
        }
        else if (keyboardRect.origin.y == [[UIScreen mainScreen] bounds].size.height){//让键盘消失
            CGRect rect =messageInputView.frame;
            rect.origin.y += CGRectGetHeight(keyboardRect);
            [UIView animateWithDuration:keyboardAnimationDuration animations:^{
                messageInputView.frame = rect;
            } completion:^(BOOL finished) {
                
            }];
        }
    }
}

- (void)keyboardWillShow:(NSNotification *)notification{
    keyboardRect = [[notification.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    keyboardAnimationDuration = [[notification.userInfo valueForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//    NSLog(@"keyboardWillShow x=%f y=%f width=%f height=%f  duration=%f",keyboardRect.origin.x,keyboardRect.origin.y,keyboardRect.size.width,keyboardRect.size.height,keyboardAnimationDuration);

}
- (void)keyboardWillHide:(NSNotification *)notification{
    keyboardRect = [[notification.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    keyboardAnimationDuration = [[notification.userInfo valueForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
//    NSLog(@"keyboardWillHide x=%f y=%f width=%f height=%f  duration=%f",keyboardRect.origin.x,keyboardRect.origin.y,keyboardRect.size.width,keyboardRect.size.height,keyboardAnimationDuration);
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
//    [instance release];
//    [super dealloc];
}
- (void)resetLabelHeight:(UITextView *)textView
{
    CGSize size = [textView sizeThatFits:CGSizeMake(textView.frame.size.width, 70)];
//    NSLog(@"1==========%f",size.height);
    
    BOOL isShrinking = size.height < self.previousTextViewContentHeight;
    CGFloat changeInHeight = size.height - self.previousTextViewContentHeight;
    
    if(!isShrinking && self.previousTextViewContentHeight == 70) {
        changeInHeight = 0;
    }
    else {
        changeInHeight = MIN(changeInHeight, 70 - self.previousTextViewContentHeight);
    }
    if(changeInHeight != 0.0f) {
        
        [UIView animateWithDuration:0.25f
                         animations:^{
                             
                             if(isShrinking) {
                                 // if shrinking the view, animate text view frame BEFORE input view frame
                                 [self adjustTextViewHeightBy:changeInHeight];
                             }
                             
                             CGRect inputViewFrame = messageInputView.frame;
                             messageInputView.frame = CGRectMake(inputViewFrame.origin.x,
                                                                 inputViewFrame.origin.y - changeInHeight,
                                                                 inputViewFrame.size.width,
                                                                 inputViewFrame.size.height + changeInHeight);
                             [messageInputView resetSubviewsFrame];
                             if(!isShrinking) {
                                 [self adjustTextViewHeightBy:changeInHeight];
                             }
                         }
                         completion:^(BOOL finished) {
                         }];
        self.previousTextViewContentHeight = MIN(size.height, 70);
    }
        CGPoint bottomOffset = CGPointMake(0.0f, messageInputView.inputTextView.contentSize.height - messageInputView.inputTextView.bounds.size.height);
        [messageInputView.inputTextView setContentOffset:bottomOffset animated:YES];
}

@end
